package com.kecheng.action;

/**
 * 测试action
 */

import com.kecheng.com.utils.BeanHelper;
import com.kecheng.com.utils.CommonUtil;
import com.kecheng.com.utils.WxUserHelpper;
import com.kecheng.dao.PeizhiDao;
import com.kecheng.dto.TiMuDto;
import com.kecheng.dto.TmSourceDto;
import com.kecheng.dto.WebCommonsResponse;
import com.kecheng.pojo.*;
import com.kecheng.util.SpringUtil;
import org.apache.struts2.convention.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@ParentPackage("json-default")
@Action(value = "test", interceptorRefs = {@InterceptorRef("json")}, results = {
        @Result(name = "teamkaoshi", type = "json", params = {"root", "kaoshiList"}),
        @Result(name = "firtestTimus", type = "json", params = {"root", "currSources"}),
        @Result(name = "complete", type = "json", params = {"root", "kaoshi"}),
        @Result(name = "webResponse", type = "json", params = {"root", "webCommonsResponse"})
})
@AllowedMethods(value = {("regex:.*")})
public class TestAction extends BaseAction {
    private static int TIMU_COUNT = 3;

    private List<TmSource> currSources;

    private TmSource tmSource;

    private List<Kaoshi> kaoshiList;

    private List<TestDetail> testDetails;

    private Kaoshi kaoshi;

    /**
     * 开出考试时间
     */
    private Date startDate;

    /**
     * 微信端查询周测记录
     */
    public String wsSelectTestRecords() {
        Kaoshi kaoShi = new Kaoshi();
        kaoShi.setOpenId(WxUserHelpper.getOpenid());
        kaoShi.setType(2);
        kaoshiList = dao.getHibernateTemplate().findByExample(kaoShi);
        return "teamkaoshi";
    }

    /**
     * 首次测试题生成
     */
    public String fetchTimus() {
        if (tmSource == null) {
            tmSource = new TmSource();
            tmSource.setType("1");
        }
        List<TmSource> tmSources = (List<TmSource>) dao.find(tmSource);

        currSources = new ArrayList<>();//生成的题目

        Set<Integer> ids = new HashSet<>();//生成的list下标
        
        //生成15个不重复的随机下标
        Random random = new Random();
        while (ids.size() < TIMU_COUNT) {
            int r = random.nextInt(tmSources.size());
            ids.add(r);
        }

        //众tmSources里面取出15个随机题
        ids.stream().forEach(id -> currSources.add(tmSources.get(id)));

        //补冲完整大题下的小题和选项,放入dto
        currSources = currSources.stream().map(ts -> {
            TmSourceDto tsDto = new TmSourceDto();

            //取小题和选项
            TiMu timu = new TiMu();
            timu.setParentId(ts.getId());
            List<TiMu> tiMus = (List<TiMu>) dao.find(timu);

            List<TiMuDto> tmDtos = new ArrayList<>();

            //查出选项
            tiMus.stream().forEach(tm -> {
                TiMuDto tmDto = new TiMuDto();

                //取选项
                TmOption option = new TmOption();
                option.setTmId(tm.getId());
                List<TmOption> optionList = (List<TmOption>) dao.find(option);
                tmDto.setTmOptionList(optionList);

                //复制原tm进dto
                BeanHelper.copyNonNullProperties(tm, tmDto);
                tmDtos.add(tmDto);
            });

            //复制原大题进dto
            BeanHelper.copyNonNullProperties(ts, tsDto);
            tsDto.setTimus(tmDtos);
            return tsDto;
        }).collect(Collectors.toList());

        webCommonsResponse = WebCommonsResponse.ok(currSources);
        return "webResponse";
    }

    /**
     * 测试完成
     */
    @Transactional(readOnly = false)
    public String complete() {
        //初始化考试数据
        kaoshi = new Kaoshi();
        kaoshi.setStartTime(CommonUtil.dateToString(startDate));
        kaoshi.setEndTime(CommonUtil.dateToString(new Date()));
        kaoshi.setType(Integer.valueOf(tmSource.getType()));
        kaoshi.setOpenId(WxUserHelpper.getOpenid());
        Team team = WxUserHelpper.getTeam();
        kaoshi.setStudentId(team.getId());
        kaoshi.setStudentName(team.getName());

        dao.updateSave(kaoshi);

        AtomicInteger score = new AtomicInteger();

        testDetails = BeanHelper.listMapToBean(testDetails, TestDetail.class);

        //计分
        testDetails.forEach(d -> {
            d.setKaoshiId(kaoshi.getId());

            Integer timuId = d.getTimuId();

            //取正确答案
            TiMu timu = new TiMu();
            timu.setId(d.getTimuId());
            TiMu tiMu = (TiMu) dao.findOne(timu);
            String answer = tiMu.getAnswer();
            d.setCorrectAnswer(answer);

            //判对错
            if (CommonUtil.equalsString(answer, d.getStuAnswer())) {//对
                score.set(score.get() + 1);
                d.setResult(1);
            } else {
                d.setResult(0);
            }
            dao.updateSave(d);
        });

        kaoshi.setTestCode(score.toString());

        //此处直接判断是首测还是周测，直接返回相关的数据
        if("1".equals(tmSource.getType())){//首测
            List<JibieSet> testSetList= (List<JibieSet>)dao.find(JibieSet.class);
            JibieSet jibieSet = testSetList.get(0);
            Integer fenshu = Integer.valueOf(kaoshi.getTestCode());
            Teacher teacher = new Teacher();
            if(fenshu<jibieSet.getScore1()){//初级
                teacher.setLevel(1);
            }else if(fenshu<jibieSet.getScore2()){//中级
                teacher.setLevel(2);
            }else {//高级
                teacher.setLevel(3);
            }
            List<Teacher>teacherList = (List<Teacher>) dao.find(teacher);
            webCommonsResponse = WebCommonsResponse.ok(teacherList);
        }else{
            Kaoshi kaoShi = new Kaoshi();
            kaoShi.setOpenId(WxUserHelpper.getOpenid());
            kaoShi.setType(2);
            kaoshiList = dao.getHibernateTemplate().findByExample(kaoShi);
            webCommonsResponse = WebCommonsResponse.ok(kaoshiList);
        }
        return "webResponse";
    }

    public List<Kaoshi> getKaoshiList() {
        return kaoshiList;
    }

    public void setKaoshiList(List<Kaoshi> kaoshiList) {
        this.kaoshiList = kaoshiList;
    }

    public List<TmSource> getCurrSources() {
        return currSources;
    }

    public void setCurrSources(List<TmSource> currSources) {
        this.currSources = currSources;
    }

    public TmSource getTmSource() {
        return tmSource;
    }

    public void setTmSource(TmSource tmSource) {
        this.tmSource = tmSource;
    }


    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public List<TestDetail> getTestDetails() {
        return testDetails;
    }

    public void setTestDetails(List<TestDetail> testDetails) {
        this.testDetails = testDetails;
    }

    public Kaoshi getKaoshi() {
        return kaoshi;
    }

    public void setKaoshi(Kaoshi kaoshi) {
        this.kaoshi = kaoshi;
    }
}
